package com.jhw.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jhw.ymcc.domain.CourseMarket;
import com.jhw.ymcc.domain.CourseUserLearn;
import com.jhw.ymcc.dto.PayExtParamsDto;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.mapper.CourseUserLearnMapper;
import com.jhw.ymcc.service.ICourseMarketService;
import com.jhw.ymcc.service.ICourseUserLearnService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jhw.ymcc.util.AssertUtil;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-10-03
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {

    @Autowired
    private ICourseMarketService courseMarketService;


    @Override
    public CourseUserLearn selectByCourseIdAndLoginId(Long courseId, Long loginId) {
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id", loginId);
        wrapper.eq("course_id", courseId);
        return selectOne(wrapper);
    }

    @Override
    public void saveCourseUserLearn(PayExtParamsDto payExtParamsDto) {
        String courseIds = payExtParamsDto.getCourseIds();
        Long userId = payExtParamsDto.getUserId();
        String orderNo = payExtParamsDto.getOrderNo();
        AssertUtil.isNotEmpty(courseIds, GlobalErrorCode.ERROR);
        AssertUtil.isNotNull(userId, GlobalErrorCode.ERROR);
        AssertUtil.isNotEmpty(orderNo, GlobalErrorCode.ERROR);
        String[] ids = courseIds.split(",");

        List<Long> collect = Arrays.stream(ids).map(id -> Long.valueOf(id)).collect(Collectors.toList());
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id", userId);
        List<CourseUserLearn> courseUserLearns = selectList(wrapper);

        Map<Long, CourseUserLearn> courseUserLearnMap = null;
        if (courseUserLearns != null && courseUserLearns.size() > 0){
            // 1.用户买过课程
            courseUserLearnMap = courseUserLearns.stream().collect(Collectors.toMap(CourseUserLearn::getCourseId, courseUserLearn -> courseUserLearn));
        }else {
            // 2.用户从来没买过
            courseUserLearnMap = new HashMap<>();
        }

        Map<Long, CourseMarket> courseMarketMap = courseMarketService.selectBatchIds(collect).stream().collect(Collectors.toMap(CourseMarket::getId, courseMarket -> courseMarket));

        Date now = new Date();
        for (Long courseId : collect) {
            CourseUserLearn courseUserLearn = courseUserLearnMap.get(courseId);
            CourseMarket courseMarket = courseMarketMap.get(courseId);
            Integer validDays = courseMarket.getValidDays();

            if (courseUserLearn != null){
                if (courseUserLearn.getState().equals(CourseUserLearn.NO_STATE)){
                    // 2.用户买了过期了
                    courseUserLearn.setState(CourseUserLearn.YES_STATE);
                    courseUserLearn.setStartTime(now);
                    courseUserLearn.setEndTime(DateUtils.addDays(now, validDays));
                    courseUserLearn.setCourseOrderNo(orderNo);
                }else {
                    // 3.用户买了并且没有过期还要续费-加时间
                    courseUserLearn.setEndTime(DateUtils.addDays(courseUserLearn.getEndTime(), validDays));
                    courseUserLearn.setCourseOrderNo(orderNo);
                }
                updateById(courseUserLearn);
            }else {
                courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(courseId);
                courseUserLearn.setLoginId(userId);
                courseUserLearn.setCreateTime(now);

                courseUserLearn.setCourseOrderNo(orderNo);
                courseUserLearn.setStartTime(now);
                // DateUtils.addDays(now, validDays)：当前时间+你指定的天数
                courseUserLearn.setEndTime(DateUtils.addDays(now, validDays));
                courseUserLearn.setState(CourseUserLearn.YES_STATE);
                insert(courseUserLearn);
            }

        }
    }
}
